if(!window.g_hzcf_wsconnect) /*客户端是否连接*/
	window.g_hzcf_wsconnect = null;

if( !window.g_notifycation ) /*插件保存websocket信息*/
	window.g_notifycation = null;
if( !window.g_hzcf_cnt )
    window.g_hzcf_cnt = 5;

var c_cfg_ping = 1000*240; /*4 分钟*/
var c_ipaddr;    /*OM适配器地址*/
var c_uid;     /* 用户ID */
var c_omid;   /*OM设备编号。 */
var c_extid; /*分机号*/
var c_tab_id;/*TAB编号*/
var c_win_id;/*窗口编号*/
var c_line;/*线路编号*/

chrome.extension.onRequest.addListener(
  	function(request, sender, sendResponse) {
        /*向OM设备推送消息*/
        if( request.om_notify && request.data ){
            if( request.data && g_hzcf_wsconnect ){
                sendResponse({rcode:1});
                g_hzcf_wsconnect.send( JSON.stringify( request.data) );
            }
            else
                sendResponse({rcode:0});
        }

  		/*建立websocket请求,请求参数为分机ID,OM设备编号*/
  		if(request.addr && request.omID && request.extID && request.uid){
            if( c_extid != request.extID  || c_omid != request.omID || c_ipaddr != request.addr ){
                hzcf_clear();
                if( g_hzcf_wsconnect ){
                    g_hzcf_wsconnect.close();
                    g_hzcf_wsconnect = null;
                    window.g_hzcf_cnt = 5;
                }
            }
            c_tab_id = sender.tab.id;
            c_win_id = sender.tab.windowId;
  			c_ipaddr = request.addr;
            c_uid = request.uid;    
            c_omid = request.omID;
            c_extid = request.extID;
            if( null != window.g_hzcf_wsconnect  )
                sendResponse({msg:1,line:c_line});
            else
                hzcf_wsconnect(c_uid, c_omid, c_extid,c_ipaddr, sendResponse);
  		}
	});

function hzcf_wshandle( _type, _msg,sendResponse){
    if( 'msg' == _type ){ // websocket message
        if( _msg ){
             try{
                a = JSON.parse( _msg );
                if( typeof a.rcode !== "undefined"  ){
                    if( a.rcode < 1 ){
                        return false;
                    }
                }
                if( 'init' == a.op ){
                    if( g_notifycation )
                        g_notifycation.cancel();
                    chrome.tabs.sendRequest( c_tab_id ,{op: a.op,data:a.data,hzcf:1},  function(response) {});
                    c_line = a.data.lineid;
                    hzcf_notify({title:'电话分机',img:'ext.png',msg:'登录成功'}, false, 1000);
                }
                else if( 'answer' == a.op || 'answered' == a.op || 'cdr' == a.op || 'bye' == a.op){
                   chrome.tabs.sendRequest(c_tab_id ,{op: a.op,data:a.data,hzcf:1},  function(response) {}); 
                }
                else if( 'incoming' == a.op  ){
                    chrome.tabs.sendRequest(c_tab_id ,{op: a.op,data:a.data,exts:a.exts,hzcf:1},  function(response) {});
                    hzcf_notify({title:'来电',img:'call.png',msg:a.data['area'] + ' '+ a.data['from'] }, true, 5000); 
                }
                else if( 'offline' == a.op  ){
                    chrome.tabs.sendRequest(c_tab_id ,{op:a.op,data:a.msg,hzcf:1},  function(response) {}); 
                }
                else if('dail' == a.op){
                     chrome.tabs.sendRequest(c_tab_id,{op:'dail',hzcf:1,data:a.data,area:a.area},function(response){});
                }
                else if('extchange' == a.op ){
                    //
                } 
                else if('broadcast' == a.op ){
                     hzcf_notify({title:'广播消息',img:'broadcast.png',msg:a.data }, false, 2000);
                }
             }catch(e){
                console.log( e );
               console.log("推送消息解析失败:" + _msg );
            }
        }
    }
    else if('op' == _type ){ //

    }
    else if( 'notify' == _type ){
        //
    }
}

function hzcf_notify( _msg, _back2chrome, _autoclose ){
    if( g_notifycation )
        g_notifycation.cancel();
     g_notifycation = chrome.notifications.create(null, opt = {
                  type: "basic",
                  title: _msg.title,
                  message: _msg.msg,
                  iconUrl: "img/" + _msg.img,
                },null ); 
     if( g_notifycation )   g_notifycation.show();
    if( _back2chrome ) {
         chrome.windows.update(c_win_id,{focused:true,drawAttention:true,},null); 
         chrome.tabs.update( c_tab_id,{active:true},null);
     }
    if( _autoclose )    window.setTimeout(closeGMsg, _autoclose);
}

function closeGMsg()
{
    if(g_notifycation)
        g_notifycation.cancel();
}

//清理用户缓存信息，表示不需要再断线重连。
function hzcf_clear()
{ 
    c_uid = null;
    c_omid = null;
    c_extid = null; 
}

function hzcf_ws_heartline(){
    if( g_hzcf_wsconnect ){
        var ping = {};
        ping.op = 'ping';
        ping.data = 'pong';
        g_hzcf_wsconnect.send( JSON.stringify( ping ) );
        setTimeout(function(){ hzcf_ws_heartline();},c_cfg_ping);  
    }
 
}


function hzcf_wsconnect( _uid, _omid, _extid, _addr,sendResponse){
        if( g_hzcf_wsconnect != null || !_uid || !_omid || !_addr || !_extid){
            return false;
        }
        if( g_hzcf_cnt ){
            g_hzcf_cnt --;
        }
        else{
            console.log( g_hzcf_cnt );
             hzcf_notify({title:'电话分机',img:'ext.png',msg:'超过最大登录次数'}, false, false);
             return false;
        }
        var serveruripre = "ws://" + _addr + '/ws';
        var fulluri = serveruripre + "?omID="+_omid+"&subID="+_extid+"&UID="+_uid;
        console.log( fulluri );
        g_hzcf_wsconnect = new WebSocket(fulluri);
        g_hzcf_wsconnect.onopen = function() {
            if( g_notifycation )
                g_notifycation.cancel();
            sendResponse({msg:1,line:''});
            g_hzcf_cnt = 5;
             setTimeout(function(){ hzcf_ws_heartline();},c_cfg_ping);  
        };  

        g_hzcf_wsconnect.onerror = function( error ){
            sendResponse({msg:0});
        };
        g_hzcf_wsconnect.onmessage = function (evt) { 
            console.log('ws接收到消息，data:');
            console.log( evt.data);
            if( sendResponse  )
                hzcf_wshandle('msg',evt.data,sendResponse);
            else
                hzcf_wshandle('msg',evt.data);
        };  
        g_hzcf_wsconnect.onclose = function() {
            if(c_omid && c_extid)
            {
                g_hzcf_wsconnect = null;
                hzcf_notify({title:'电话分机',img:'ext.png',msg:'与服务器端['+_addr+']的连接中断，等待5秒后将自动重连。'}, false, 5000);
                setTimeout(function(){
                    hzcf_wsconnect(_uid,_omid,_extid,_addr,sendResponse);
                },5000);
            }
            else
                hzcf_notify({title:'电话分机',img:'ext.png',msg:'与服务器端['+_addr+']的连接已经断开！'}, false, false);
            
        };
}